package com.tiku.service.impl;

import com.tiku.common.ResultJson;
import com.tiku.controller.DTO.UserCollectionDTO;
import com.tiku.entity.QuestionTable;
import com.tiku.entity.UserQuestionLog;
import com.tiku.mapper.QuestionTableMapper;
import com.tiku.mapper.UserCollectionMapper;
import com.tiku.service.UserErrorCollectionService;
import com.tiku.utils.RedisCache;
import com.tiku.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * @author 小马不会跑
 * @create 2024-10-01 2:13
 */
@Service
public class UserErrorCollectionServiceImpl implements UserErrorCollectionService {

    @Autowired
    private QuestionTableMapper tableMapper;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private UserCollectionMapper userCollectionMapper;

    @Autowired
    private QuestionTableMapper questionTableMapper;
//    查询收藏榜或者错题榜
    @Override
    public ResultJson getError(String id,String type) {
        if (StringUtils.isEmpty(type)){
            return ResultJson.error("查询类型不能为空！");
        }
        if ("0".equals(type)){
            //错题榜
            Collection<String> keys = redisCache.keys("questionLog:*" + id + "*");
            List<UserQuestionLog> logList = new ArrayList<>();
            for (String key : keys) {
                UserQuestionLog log= redisCache.getCacheObject(key);
                if (0==log.getRightflag()){
                    logList.add(log);
                    String questionId = log.getQuestionId();
                    QuestionTable questionTable = tableMapper.selectById(questionId);
                    log.setQuestionTable(questionTable);

                }
            }

            logList = logList.subList(0, Math.min(100, logList.size()));
            return ResultJson.success(logList);
        }else if("1".equals(type)){
            //收藏榜
            //查询的是chapter_info
            List<UserCollectionDTO> userCollection = userCollectionMapper.selectCollection3(id);

            //查询的是chapter_sub_info
            List<UserCollectionDTO>  userCollection2=userCollectionMapper.selectCollection4(id);
            userCollection.addAll(userCollection2);

            for (UserCollectionDTO userCollectionDTO : userCollection) {
                QuestionTable questionTable = questionTableMapper.selectById(userCollectionDTO.getId());
                questionTable.setCollectFlagDO(true);
                userCollectionDTO.setQuestionTable(questionTable);
            }
            userCollection=userCollection.subList(0, Math.min(100, userCollection.size()));
            return ResultJson.success(userCollection) ;
        }else {
            return ResultJson.sysError();
        }



    }


}
